/*
 * Copyright 2012 Finbudget.com
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package finbudgettable.client.ui.grid.cell.description;

import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.FieldUpdater;
import finbudget.client.ui.table.Record;
import finbudgettable.client.ui.grid.CellGrid;
import finbudgettable.client.ui.grid.cell.CommonComparator;
import finbudgettable.client.ui.grid.cell.string.StringFilterPanel;
import finbudgettable.client.ui.grid.column.ColumnMenu;
import finbudgettable.client.ui.grid.column.ColumnMenuImpl;
import finbudgettable.client.ui.grid.column.GridColumn;

public class DescriptionColumn extends GridColumn<String> {

    public DescriptionColumn(Builder builder) {
        super(builder);
        initFieldUpdater(builder.getFieldName());
    }

    @Override
    protected boolean isValueChanged(Record record, String value) {
        return CommonComparator.isNotEqual(getValue(record), value);
    }

    @Override
    protected String getCellStyleNames() {
        return DescriptionCell.RESOURCES.style().bDescriptionCell();
    }

    private void initFieldUpdater(final String fieldName) {
        setFieldUpdater(new FieldUpdater<Record, String>() {
            public void update(int index, Record record, String value) {
                record.setValue(fieldName, value);
            }
        });
    }

    @Override
    public String getValue(Record record) {
        return record.getValueString(getFieldName());
    }

    public static class Builder extends GridColumn.Builder<DescriptionCell, String> {

        Builder(CellGrid grid, String fieldName, boolean hasTotals) {
            super(grid, fieldName, hasTotals);
        }

        @Override
        protected DescriptionCell createCell() {
            return new DescriptionCell();
        }

        public ColumnMenu getDefaultColumnMenu() {
            final ColumnMenu columnMenu = new ColumnMenuImpl(grid, new StringFilterPanel(fieldName));
            setColumnMenu(columnMenu);
            return columnMenu;
        }

        @Override
        protected GridColumn<String> createColumn(Cell<String> cell) {
            return new DescriptionColumn(this);
        }
    }

    public static Builder builder(CellGrid grid, String fieldName, boolean hasTotals) {
        return new Builder(grid, fieldName, hasTotals);
    }
}
